var express = require('express');
var fs = require('fs');
var router = express.Router();
// var userController   = require('../controllers/user/IndexController.js');

//读取目录
function readFileList(path, filesList) {
    var files = fs.readdirSync(path);
    files.forEach(function (itm, index) {
        var stat = fs.statSync(path + itm);
        if (stat.isDirectory()) {
        //递归读取文件
            readFileList(path + itm + "/", filesList)
        } else {
            var obj = {};//定义一个对象存放文件的路径和名字
            if(path.split('/').length==4 && itm.split('Controller').length==2){
            	obj.path = path.split('/')[2];//路径
            	obj.filename = itm//名字
            	filesList.push(obj);
            }
            
        }
    })
}
var getFiles = {
    //获取文件夹下的所有文件
    getFileList: function (path) {
        var filesList = [];
        readFileList(path, filesList);
        return filesList;
    }
};

var dirNameList = getFiles.getFileList("./controllers/")


/**
 * [myrouter 封装路由]
 * @param  {[type]} firstRouretName  [description]
 * @param  {[type]} secondRouretName [description]
 * @param  {[type]} routers          [description]
 * @return {[type]}                  [description]
 */
function myrouter(firstRouretName,secondRouretName,routers){
	var routers = routers
	var rourersName = []
	var secondRouretName = secondRouretName
	//一级路由名称
	var firstRouretName = firstRouretName
	//获取router名
	for (var name in routers) {rourersName.push(name)}
	for (var i =0; i<rourersName.length;i++){
		if(rourersName[i].indexOf('get_')>-1){
			var name = rourersName[i].substring(4,rourersName[i].length)
			// console.log('/'+firstRouretName+'/'+name+'/'+secondRouretName+'')
		
			router.get('/'+firstRouretName+'/'+secondRouretName+'/'+name+'', routers[rourersName[i]]);
		}else if(rourersName[i].indexOf('post_')>-1){
			var name = rourersName[i].substring(5,rourersName[i].length)
			router.post('/'+firstRouretName+'/'+secondRouretName+'/'+name+'', routers[rourersName[i]]);
		}
	}
}
for (var i =0; i<dirNameList.length;i++){
	var secondRouretName = dirNameList[i].filename.split('Controller')[0]
	var controller = require('../controllers/'+dirNameList[i].path+'/'+dirNameList[i].filename+'')
	//console.log(require('../controllers/'+dirNameList[i].path+'/'+dirNameList[i].filename+''))
	myrouter(dirNameList[i].path,secondRouretName,controller)
}

module.exports = router;